package com.example.starter.config;

import com.example.starter.properties.CrossOriginProperties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@EnableConfigurationProperties({CrossOriginProperties.class})
@AutoConfigureAfter(CrossOriginProperties.class)
@Configuration
public class CrossOriginFilter implements Filter {
    @Autowired
    private CrossOriginProperties properties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest hservletRequest = (HttpServletRequest) req;
        response.setHeader("X-Frame-Options", properties.getFrameOptions());
        response.setHeader("Access-Control-Allow-Origin", hservletRequest.getHeader("origin")); // allow all
//        response.setHeader("Access-Control-Allow-Origin", properties.getAllowOrigin());
        response.setHeader("Access-Control-Allow-Credentials", properties.getAllowCredentials());
        response.setHeader("Access-Control-Allow-Methods", properties.getAllowMethods());
        response.setHeader("Access-Control-Max-Age", properties.getMaxAge());
        response.setHeader("Cache-Control", properties.getCacheControl());
        response.setHeader("Pragma", properties.getPragma());
        response.setHeader("Access-Control-Allow-Headers", properties.getAllowHeaders());
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {

    }
}
